import re
import hashlib
import uuid
import fileinput
import sys
from tqdm import tqdm


salt = uuid.uuid4().hex


def serialize_set(obj):
    if isinstance(obj, set):
        return list(obj)
    return obj


def replace_json(s):
    hash = hashlib.sha256(salt.encode('utf8') + s.group(0).encode("utf-8"))
    hash = hash.hexdigest()
    return "[\"{}\",\"{}.{}.{}.0\"]".format(hash, s.group(1), s.group(2), s.group(3))


def substitute(filename, regex, replace):
    for line in fileinput.input(filename, inplace=True):
        new = re.sub(regex, replace, line)
        sys.stdout.write(new)


def anonymize(filenames_json: list[str]):
    ip_capture_regex_json = '"([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})"'
    for filename in tqdm(filenames_json):
        substitute(filename, ip_capture_regex_json, replace_json)
